import 'dart:io';
import 'package:flutter/material.dart';
import 'package:ducafe_ui_core/ducafe_ui_core.dart';
import '../index.dart';

/// 通用用户头像组件
class UserAvatar extends StatelessWidget {
  final String? avatarPath;
  final double radius;
  final String? fallbackAsset; // 默认头像
  final BoxFit fit;
  final VoidCallback? onTap;

  const UserAvatar({
    super.key,
    this.avatarPath,
    required this.radius,
    this.fallbackAsset,
    this.fit = BoxFit.cover,
    this.onTap,
  });

  @override
  Widget build(BuildContext context) {
    Widget avatar = CircleAvatar(
      radius: radius,
      backgroundImage: _getImageProvider(),
    );

    if (onTap != null) {
      return GestureDetector(onTap: onTap, child: avatar);
    }

    return avatar;
  }

  /// 获取图片提供者
  ImageProvider _getImageProvider() {
    if (avatarPath == null || avatarPath!.isEmpty) {
      return AssetImage(fallbackAsset ?? MyImages.mark);
    }

    if (avatarPath!.startsWith('assets/')) {
      return AssetImage(avatarPath!);
    } else {
      // 本地文件路径
      final file = File(avatarPath!);
      if (file.existsSync()) {
        return FileImage(file);
      } else {
        return AssetImage(fallbackAsset ?? MyImages.mark);
      }
    }
  }
}

/// 方形用户头像组件
class UserAvatarSquare extends StatelessWidget {
  final String? avatarPath;
  final double size;
  final String? fallbackAsset;
  final BoxFit fit;
  final VoidCallback? onTap;
  final double borderRadius;

  const UserAvatarSquare({
    super.key,
    this.avatarPath,
    required this.size,
    this.fallbackAsset,
    this.fit = BoxFit.cover,
    this.onTap,
    this.borderRadius = 10.0,
  });

  @override
  Widget build(BuildContext context) {
    Widget avatar = Container(
      width: size,
      height: size,
      decoration: ShapeDecoration(
        image: DecorationImage(image: _getImageProvider(), fit: fit),
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(borderRadius.r),
        ),
      ),
    );

    if (onTap != null) {
      return GestureDetector(onTap: onTap, child: avatar);
    }

    return avatar;
  }

  /// 获取图片提供者
  ImageProvider _getImageProvider() {
    if (avatarPath == null || avatarPath!.isEmpty) {
      return AssetImage(fallbackAsset ?? MyImages.mark);
    }

    if (avatarPath!.startsWith('assets/')) {
      return AssetImage(avatarPath!);
    } else {
      // 本地文件路径
      final file = File(avatarPath!);
      if (file.existsSync()) {
        return FileImage(file);
      } else {
        return AssetImage(fallbackAsset ?? MyImages.mark);
      }
    }
  }
}
